import axios from 'axios'
import { ElMessageBox, ElMessage } from 'element-plus'
import store from '@/store'
import { getToken } from '@/utils/auth'

export let isRelogin = { show: false };
// create an axios instance
const service = axios.create({

  //baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: 'http://127.0.0.1:8888',
  //baseURL:"127.0.0.1:9999",
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000, // request timeout
  headers: { "Content-Type": "application/json;charset=utf-8" },
})

// request interceptor
service.interceptors.request.use(
  config => {
    //console.log(process.env.VUE_APP_BASE_API)
    console.log("=================================",localStorage.getItem("accessToken"))
    if (localStorage.getItem("accessToken")) {
      // var token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiLml4XkuroiLCJzY29wZSI6WyJhbGwiXSwiaWQiOiIzODE0OTYiLCJleHAiOjE2Nzk1NTc5ODIsImF1dGhvcml0aWVzIjpbIkFETUlOIl0sImp0aSI6IjQxZDhhMzlmLWI2MzMtNDI1NC1iMWNkLWEwOWM4OGY3ZWI2MyIsImNsaWVudF9pZCI6ImNsaWVudC1hcHAifQ.WjCumpI-ocUrAuHPJKaHyVerhRTl2gpXayQ6YhhWI-g";
      //var token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJsaXNpIiwic2NvcGUiOlsiYWxsIl0sImlkIjoiNjE3Njk3OTgiLCJleHAiOjE2Nzk1NTgxMzQsImF1dGhvcml0aWVzIjpbIkFETUlOIl0sImp0aSI6IjMyOWRiZTA3LWQzMGUtNGYyMi04NzliLTczYzA3Yzk5NmEyMiIsImNsaWVudF9pZCI6ImNsaWVudC1hcHAifQ.qgIm_gWnvjQa3nX0XSQKTyY3pNzyAWH81pFhLh9rwRg";
      var token = localStorage.getItem("accessToken");
      config.headers.Authorization =  token;

    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)


// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    console.log("-------------0101010101",JSON.stringify(res))
    // if the custom code is not 20000, it is judged as an error.
    if (res.status !== 0) {
      ElMessage({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.status === 50008 || res.status === 50012 || res.status === 50014) {
        // to re-login
        ElMessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/restToken').then(() => {
            console.log("成功+")
            location.reload()
          })
        })
      } else if(res.status === 11008) {
        // to re-login
        // ElMessageBox.confirm('登陆过期', 'Confirm logout', {
        //   confirmButtonText: 'Re-Login',
        //   cancelButtonText: 'Cancel',
        //   type: 'warning'
        // }).then(() => {
          store.dispatch('user/refreshToken').then((res) => {
            console.log("成功+res")
            location.reload()
          //})
        }).catch(() => { // refresh_token也过期，直接跳转登录页面重新登录
          ElMessageBox.confirm('当前页面已失效，请重新登录', '确认退出', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.href = '/login';
            })
          })
      })}
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    ElMessage({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
let loadingInstance;

// 拦截器的添加
// service.interceptors.request.use(
//     (config) => {
//       loadingInstance = ElLoading.service("加载中");
//       return config;
//     },
//     (err) => {
//       loadingInstance?.close();
//       ElMessage.error("网络异常");
//       return Promise.reject(err);
//     }
// );

// //响应拦截器
// service.interceptors.response.use(
//     (res) => {
//       loadingInstance?.close();
//       return res.data;
//     },
//     (err) => {
//       loadingInstance?.close();
//       ElMessage.error("请求失败");
//       return Promise.reject(err);
//     }
// );

export default service
